<?php

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\SMember as MemberModel;
use think\Exception;

class SMember
{
    public $memberObj = null;
    public function __construct()
    {
        $this->memberObj = new MemberModel();
    }
    public function login($data){
        //生成token
        $memberData = $this->memberObj->getMemberByOpenid($data['unionid']);
        if($memberData){
            $updateData = [
                'wechat_nickname'   => $data['nickname'],
                'wechat_avatar_url' => $data['avatar_url'],
                'update_time'       => date("Y-m-d H:i:s",time()),
            ];
            $res = $this->memberObj->updateMember($memberData['member_id'],$updateData);
            $member_id = $memberData['member_id'];
        }else{
            $openid_key = config("wx.".$data['appid'].".WECHAT_OPENID");
            $insertData = [
                'wechat_nickname'   => $data['nickname'],
                'wechat_avatar_url' => $data['avatar_url'],
                'wechat_unionid'    => $data['unionid'],
                'create_time'       => date("Y-m-d H:i:s",time()),
                'update_time'       => date("Y-m-d H:i:s",time()),
                $openid_key         => $data['openid'],
            ];
            $res = $this->memberObj->addMember($insertData);
            $member_id = $res;
        }
        //需要记录信息到mysql表中
        if(empty($res)){
            throw new Exception("登录失败");
        }

        $token = Str::getLoginToken($data['openid']);
        $redisData = [
            "member_id"=>$member_id,
            "openid"=>$data['openid'],
        ];
        $res = cache(config("redis.token_pre").$token,$redisData,Time::userLoginExpiresTime());
        return $res ? ["token"=>$token,"member_id"=>$member_id] : false;
    }
}
